package com.erp.module.zhichengJianyan

import android.app.Activity
import androidx.appcompat.app.AlertDialog
import android.content.Intent
import android.util.Log
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.AdapterView
import com.erp.CaptureActivity
import com.erp.Myapp
import com.erp.R
import com.erp.bean.JieHaoKBean
import com.erp.bean.ProcessInspectionJieHaoBean
import com.erp.mclass.QuanXian
import com.erp.mclass.UnCeHandler
import com.erp.module.jiehao.IJieHaoP
import com.erp.module.jiehao.JieHaoContract
import com.erp.module.jiehao.scJieHao.ScJieHaoKActivity
import com.erp.module.zhichengJianyan.XXInspection.XxInspectionActivity
import com.erp.myAdapter.ArrayAdapter
import com.erp.myAdapter.InspectionAdapter
import com.erp.myAdapter.ZhiXiangKAdapter
import com.erp.myFragment.BaseKFragment
import com.erp.permission.PermissionListener
import com.erp.util.Dialogutil
import com.erp.util.Myutil
import com.erp.util.PermissionUtils
import com.erp.view.PullToRefreshView
import kotlinx.android.synthetic.main.fragment_inspection.*
import java.util.*

class FragmentProcessInspection : BaseKFragment(),  ProcessInspectionContract.InspectionJieHaoView, View.OnClickListener, PullToRefreshView.OnHeaderRefreshListener, PullToRefreshView.OnFooterRefreshListener, AdapterView.OnItemClickListener {

    lateinit var P: IProcessInspection
    lateinit var adapter: InspectionAdapter
    lateinit var jiehaolist: MutableList<ProcessInspectionJieHaoBean>
    var updialog: AlertDialog? = null
    lateinit var sousuobean : InspectionSouSuobean
    var zhiliangid: MutableList<String> = ArrayList()
    var zhiliangname: MutableList<String> = ArrayList()
    private val f = "FragmentProcessInspection"
    override fun getLayoutId(): Int {
        fragmentname = f
        return R.layout.fragment_inspection
    }

    override fun initData() {
        sousuobean = InspectionSouSuobean()
        jiehaolist = ArrayList()
        TvStartTime.text = Myutil.getjulidate(-1)
        TvEndTime.text = Myutil.getjulidate(0)
        P = IProcessInspection( jiehaolist, this, activity!!,sousuobean)
        adapter = InspectionAdapter(jiehaolist, activity!!, P)
        InspectionLv.adapter = adapter
        InspectionLv.onItemClickListener = this
        InspectionFragmentPv.setheader(true)
        InspectionFragmentPv.setOnHeaderRefreshListener(this)
        InspectionFragmentPv.setOnFooterRefreshListener(this)
        TvStartTime.setOnClickListener(this)
        TvEndTime.setOnClickListener(this)
        iv_scan.setOnClickListener(this)
        BtGuolv.setOnClickListener(this)
        TvChongzhi.setOnClickListener(this)
        Et_code.hint = "输入物料条码"

        atWuLiaoLeiBie.setOnClickListener { atWuLiaoLeiBie.showDropDown() }

        Et_code.setOnEditorActionListener { v, actionId, event ->
            var isOK = true
            when (actionId) {
                EditorInfo.IME_ACTION_SEARCH -> {
                    getSousuo()
                    P.xiala()
                    updialog = Myutil.showupdatedialog(activity, "正在搜索节号数据", false)
                    Myutil.notjianpan(activity,iv_scan)
                }
                else -> isOK = false
            }
            isOK
        }
        val listsp = ArrayList<String>()
        listsp.add("计划入仓时间")
        listsp.add("检验时间")
        val adaptertime = ArrayAdapter(activity, R.layout.lv_sp_tvitem, listsp)
        SpTimeCategory.adapter = adaptertime
        val listjianyansp = ArrayList<String>()
        listjianyansp.add("全部")
        listjianyansp.add("已检验")
        listjianyansp.add("未检验")
        val adapterjianyan = ArrayAdapter(activity, R.layout.lv_sp_tvitem, listjianyansp)
        SpInspection.adapter = adapterjianyan
        getSousuo()
        P.gainData("inspection")
        InspectionFragmentPv.headerRefreshing()
        P.getWuLiao_DaiMa()
    }

    fun getSousuo(){
        sousuobean = InspectionSouSuobean()
        sousuobean.code = Et_code.text.toString()
        sousuobean.inspection = SpInspection.selectedItem.toString()
        if(SpTimeCategory.selectedItem.toString() == "计划入仓时间"){
            sousuobean.time_category = "mb.plan_warehousing_time";
        }else if(SpTimeCategory.selectedItem.toString() == "检验时间"){
            sousuobean.time_category = "pi.ctime";
        }
        sousuobean.start_time = TvStartTime.text.toString()
        sousuobean.end_time = TvEndTime.text.toString()

        if (zhiliangname.contains(atWuLiaoLeiBie.text.toString())) {
            zhiliangname.indices
                    .filter { zhiliangname[it] == atWuLiaoLeiBie.text.toString() }
                    .forEach { sousuobean.wuliao = zhiliangid[it] }
        }
        sousuobean.quhao = etQuhao.text.toString()
        P.sousuo(sousuobean)
    }

    fun qingkong() {
        if (!isFirstLoad) {
            return
        }
        isFirstLoad = false
        InspectionFragmentPv.headerRefreshing()
    }

    override fun InspectionJieHaoOk(data: String) {
        if (updialog != null) {
            updialog?.dismiss()
        }
        P.xiala()
        updialog = Myutil.showupdatedialog(activity, "正在刷新数据", false)

    }

    override fun InspectionJieHaoNo(erroe: String) {
        if (updialog != null) {
            updialog?.dismiss()
        }
        Myutil.MyTost(Myutil.decodeUnicode(erroe))
        Log.d("TAAAG", "erroe=" + erroe)
    }

    override fun Inspectionjiehao() {
        updialog = Myutil.showupdatedialog(activity, "正在访问服务器", false)
    }


    override fun onClick(v: View?) {
        when (v) {
            iv_scan -> {
                PermissionUtils.issaomiao(activity!!,object : PermissionListener {
                    override fun onSucceed(requestCode: Int, grantPermissions: MutableList<String>) {
                        val intent = Intent(activity, CaptureActivity::class.java)
                        intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP
                        startActivityForResult(intent, 1)
                    }

                    override fun onFailed(requestCode: Int, deniedPermissions: MutableList<String>) {
                        Myutil.MyTost("没有权限，无法扫描")
                    }

                })
            }
            BtGuolv -> {
                getSousuo()
                P.xiala()
                updialog = Myutil.showupdatedialog(activity, "正在搜索节号数据", false)
                Myutil.notjianpan(activity, iv_scan)
            }
            TvChongzhi -> {
                Et_code.setText("")
                SpInspection.setSelection(0)
                SpTimeCategory.setSelection(0)
                TvStartTime.text = Myutil.getjulidate(-30)
                TvEndTime.text = Myutil.getjulidate(0)
                getSousuo()
                P.xiala()
                updialog = Myutil.showupdatedialog(activity, "正在刷新节号数据", false)
                Myutil.notjianpan(activity, iv_scan)
            }
            TvStartTime -> {
                Dialogutil.showBottoPopupWindow(TvStartTime, "选择开始时间", TvStartTime.text.toString(), activity)
            }
            TvEndTime -> {
                Dialogutil.showBottoPopupWindow(TvEndTime, "选择开始时间", TvEndTime.text.toString(), activity)
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        Log.d("TAAAG",resultCode.toString())
        super.onActivityResult(requestCode, resultCode, data)
        if(data==null||resultCode!= Activity.RESULT_OK){
            return
        }
        Log.d("TAAAG",requestCode.toString())
        when(requestCode){
            1 -> {
                val bundle = data.extras
                val s = bundle?.get("result") as String
                Et_code.setText(s)
            }
            3 -> {
                InspectionFragmentPv.headerRefreshing()
            }
        }
    }

    override fun xialaOk() {
        updialog?.dismiss()
        InspectionFragmentPv?.onHeaderRefreshComplete()
        adapter.notifyDataSetChanged()
    }

    override fun xialaNo() {
        updialog?.dismiss()
        InspectionFragmentPv?.onHeaderRefreshComplete()
    }

    override fun shanglaOk() {
        updialog?.dismiss()
        InspectionFragmentPv?.onFooterRefreshComplete()
        adapter.notifyDataSetChanged()
    }

    override fun shanglaNo() {
        updialog?.dismiss()
        InspectionFragmentPv?.onFooterRefreshComplete()
    }

    override fun gainDataOk() {
        adapter.notifyDataSetChanged()
    }

    override fun onFooterRefresh(view: PullToRefreshView) {
        P.shangla()
    }

    override fun onHeaderRefresh(view: PullToRefreshView) {
        P.xiala()
    }

    override fun onItemClick(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
        UnCeHandler.buzhou = "onItemClick"
        val intent = Intent(activity, XxInspectionActivity::class.java)
        intent.putExtra("id", jiehaolist[position].inspection_id)
        intent.putExtra("batch", jiehaolist[position].batch)
        startActivityForResult(intent, 3)
    }

    override fun getWuLiao_DaiMaOK(zhiliangid: MutableList<String>, zhiliangname: MutableList<String>) {
        this.zhiliangid=zhiliangid
        this.zhiliangname=zhiliangname
        Log.d("getWuLiao_DaiMaOK",this.zhiliangname.toString())
        val av = ArrayAdapter(activity, android.R.layout.simple_dropdown_item_1line, this.zhiliangname)
        atWuLiaoLeiBie.setAdapter(av)
    }

    override fun getWuLiao_DaiMaNO() {
    }
}